﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System.Collections.Concurrent;

namespace Common.Framework.Core.MongoDB
{
    /// <summary>
    /// MongoDB注入类
    /// </summary>
    public class MongoFactory
    {
        /// <summary>
        /// 数据库配置
        /// </summary>
        public readonly MongoConfig mongoConfig;

        /// <summary>
        /// 数据库容器
        /// </summary>
        public static ConcurrentDictionary<string, IMongoDatabase> dbContainer = new ConcurrentDictionary<string, IMongoDatabase>();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="config"></param>
        public MongoFactory(IOptions<MongoConfig> config)
        {
            this.mongoConfig = config.Value;
        }

        /// <summary>
        /// 初始化db操作类
        /// </summary>
        /// <param name="connName"></param>
        /// <param name="appId">存在业务分库</param>
        /// <returns></returns>
        public IMongoDatabase GetDatabase(string connName)
        {
            if (dbContainer.Keys.Contains(connName))
            {
                return dbContainer[connName];
            }
            //低版本使用的授权
            MongoCredential credential = MongoCredential.CreateCredential("admin", mongoConfig.AuthUserName, mongoConfig.AuthPwd); //授权库
            return GetDB(credential, connName, mongoConfig.DefaultConnectionString);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="credential"></param>
        /// <param name="connName"></param>
        /// <param name="connString"></param>
        /// <returns></returns>
        private IMongoDatabase GetDB(MongoCredential credential, string connName, string connString)
        {
            Tuple<string, int, string, ConcurrentDictionary<string, string>> tuple = SplitConnString(connString);
            ConcurrentDictionary<string, string> otherParamDic = tuple.Item4;
            string iConnectTimeout = string.Empty;
            otherParamDic.TryGetValue("ConnectTimeout", out iConnectTimeout);
            string iConnectionLifetime = string.Empty;
            otherParamDic.TryGetValue("ConnectionLifetime", out iConnectionLifetime);
            string iMinimumPoolSize = string.Empty;
            otherParamDic.TryGetValue("MinimumPoolSize", out iMinimumPoolSize);
            string iMaximumPoolSize = string.Empty;
            otherParamDic.TryGetValue("MaximumPoolSize", out iMaximumPoolSize);

            MongoClientSettings settings = new MongoClientSettings
            {
                Credential = credential,
                Server = new MongoServerAddress(tuple.Item1, tuple.Item2),
                ConnectTimeout = TimeSpan.FromSeconds(Convert.ToInt32(iConnectTimeout ?? "30000")),
                MaxConnectionLifeTime = TimeSpan.FromSeconds(Convert.ToInt32(iConnectionLifetime ?? "300000")),
                MinConnectionPoolSize = Convert.ToInt32(iMinimumPoolSize ?? "8"),
                MaxConnectionPoolSize = Convert.ToInt32(iMaximumPoolSize ?? "256"),
            };
            var client = new MongoClient(settings);
            var db = client.GetDatabase(tuple.Item3);
            return db;
        }

        /// <summary>
        /// Tuple (主机Ip,端口,数据库名)
        /// </summary>
        /// <param name="connStr"></param>
        /// <returns></returns>
        private Tuple<string, int, string, ConcurrentDictionary<string, string>> SplitConnString(string connStr)
        {
            var hostDbInfo = connStr.Split("@")[1];
            var hostInfo = hostDbInfo.Split("/");
            var hi = hostInfo[0].Split(":");
            string host = hi[0];
            int port = Convert.ToInt32(hi[1]);

            var otherParamStrs = hostInfo[1].Split("?");
            string dbName = otherParamStrs[0];

            ConcurrentDictionary<string, string> otherParams = new ConcurrentDictionary<string, string>();
            var paramStrs = otherParamStrs[1].Split("&");
            foreach (var item in paramStrs)
            {
                var itemSplit = item.Split("=");
                otherParams.TryAdd(itemSplit[0], itemSplit[1]);
            }
            return new Tuple<string, int, string, ConcurrentDictionary<string, string>>(host, port, dbName, otherParams);
        }
    }
}